package com.group3.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.group3.dao.*;
import com.group3.domain.*;
import com.group3.exception.BusinessException;
import com.group3.exception.ExceptionEnum;
import com.group3.pojo.Page;
import com.group3.pojo.receive.TLessonListReceive;
import com.group3.pojo.result.LessonResult;
import com.group3.service.ALessonService;
import com.group3.utils.NotNull;
import com.group3.utils.Result;
import com.group3.utils.ResultUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ALessonServiceImpl implements ALessonService {

    @Resource
    private LessonMapper lessonMapper;
    @Resource
    private LessonTeacherMapper lessonTeacherMapper;
    @Resource
    private AttendanceMapper attendanceMapper;
    @Resource
    private GroupMapper groupMapper;
    @Resource
    private StudentGroupMapper studentGroupMapper;
    @Resource
    private GroupLessonMapper groupLessonMapper;
    @Resource
    private StudentLessonMapper studentLessonMapper;

    /**
     *  添加课程名
     * @Author HY
     * @Description
     * @Date  2021/06/21
     * @param: lessonName
     * @return
     * @return: com.group3.utils.Result
     **/
    @Override
    @Transactional
    public Result addLesson(String lessonName) {

        Lesson lesson = new Lesson();
        lesson.setLessonName(lessonName);
        int rs = lessonMapper.insertSelective(lesson);

        return rs > 0?ResultUtil.success("添加成功"):ResultUtil.error("添加失败");
    }

    /**
     *  删除课程名
     * @Author HY
     * @Description
     * @Date  2021/06/21
     * @param: lessonId
     * @return
     * @return: com.group3.utils.Result
     **/
    @Override
    @Transactional
    public Result deleteLesson(Integer lessonId) {

        Lesson lesson = new Lesson();
        lesson.setLessonId(lessonId);
        lesson.setState(1);

        int rs = lessonMapper.updateByPrimaryKeySelective(lesson);

        return rs > 0?ResultUtil.success("删除成功"):ResultUtil.error("删除失败");
    }

    /**
     * 查询课程名
     * @Author HY
     * @Description
     * @Date  2021/06/21
     * @param: lessonName
     * @param: page
     * @return: com.group3.utils.Result
     **/
    @Override
    @Transactional
    public Result SelectLesson(String lessonName, Page page) {

        LessonExample lessonExample = new LessonExample();
        lessonExample.createCriteria()
                .andLessonNameLike("%"+(lessonName)+"%")
                .andStateEqualTo(-1);

        //1.先开启分页
        PageHelper.startPage(page.getPageNumber(), page.getPageSize());//启动分页
//        2.执行SQL语句
        List<Lesson> lessons = lessonMapper.selectByExample(lessonExample);
//        3.获取分页信息
        PageInfo<Lesson> lessonResultPageInfo = new PageInfo<>(lessons);//获取分页信息

        return ResultUtil.success("查询成功",lessons, lessonResultPageInfo.getTotal());
    }

    /**
     * 添加学生进课程安排
     * @Author HY
     * @Description
     * @Date  2021/06/21
     * @param: lessonName
     * @param: studentIds
     * @return: com.group3.utils.Result
     **/
    @Override
    @Transactional
    public Result addStudentToLesson(String lessonName, String[][] studentIds) {
        //TODO  待测试
        //业务复杂！！！
//        用来拼接小组名称
        String zu = "组";
        String groupName = "";
        Group group = null;
        GroupLesson groupLesson = null;
        //TODO  判断小组内学生是否为空     是否有相同学生在同一个小组内
//        将学生小组迭代出来
        int i = 1;
        for (String[] students : studentIds) {
//            先生成小组
            group = new Group();
            groupName = lessonName + i + zu;//拼接小组名

            group.setGroupName(groupName);//小组名
            group.setGroupLeaderId(students[0]);//小组长id
            group.setType(1);//小组类型  0-基本小组；1-课程小组
            group.setStatue(0);//小组状态   0-使用；1-已有记录，逻辑删除；
            int rs = groupMapper.insertSelective(group);
            isRs(rs);

//            添加小组与课程的关系-小组成绩
            groupLesson = new GroupLesson();
            groupLesson.setLessonName(lessonName);//课程名
            groupLesson.setGroupId(group.getGroupId());//小组id
            rs = groupLessonMapper.insertSelective(groupLesson);
            isRs(rs);

//                生成小组内的学生信息
            StudentGroup studentGroup = null;
            StudentLesson studentLesson = null;
            for (String studentId : students) {
//                生成小组成员
                studentGroup = new StudentGroup();
                studentGroup.setGroupId(group.getGroupId());
                studentGroup.setStudentId(studentId);
                rs = studentGroupMapper.insertSelective(studentGroup);
                isRs(rs);

//                生成学生课程个人成绩
                studentLesson = new StudentLesson();
                studentLesson.setLessonName(lessonName);
                studentLesson.setStudentId(studentId);
                rs = studentLessonMapper.insertSelective(studentLesson);
                isRs(rs);
            }
            i = i +1;
        }

        return ResultUtil.success("添加成功");
    }

    public void isRs(int rs){
        if (rs < 1){
            throw new BusinessException(ExceptionEnum.DATABASE_OPERATION_ERR);
        }
    }



//---------------    课程安排      ---------------

    /**
     * 查询课程安排
     * @Author HY
     * @Description
     * @Date  2021/06/21
     * @param: lessonListReceive
     * @return
     * @return: com.group3.utils.Result<java.util.List<com.group3.pojo.result.LessonResult>>
     **/
    @Override
    @Transactional
    public Result<List<LessonResult>> selectLesson(TLessonListReceive lessonListReceive) {

        LessonExample lessonExample = new LessonExample();
        LessonExample.Criteria criteria = lessonExample.createCriteria();
        //添加查询条件
//        开始时间
        if (NotNull.judge(lessonListReceive.getStartDateTime())){
            criteria.andDateGreaterThan(lessonListReceive.getStartDateTime());
        }
//        结束时间
        if (NotNull.judge(lessonListReceive.getEndDateTime())){
            criteria.andDateLessThan(lessonListReceive.getEndDateTime());
        }
//        课程名
        if (NotNull.judge(lessonListReceive.getLessonName())){
            criteria.andLessonNameEqualTo(lessonListReceive.getLessonName());
        }
////        实训老师
//        if (lessonListReceive.getTeacherS() != null){
//            criteria.andTeacherIdEqualTo(lessonListReceive.getTeacherS());
//        }
//        责任老师
        if (NotNull.judge(lessonListReceive.getTeacherZ())){
            criteria.andTeacherIdEqualTo(lessonListReceive.getTeacherZ());
        }

        //根据实训老师查询课程（lesson_teacher表）
        LessonTeacherExample lessonTeacherExample = new LessonTeacherExample();
        lessonTeacherExample.setDistinct(true);

        // 老师查询考勤时，该teacherId为查询老师的id（andTeacherIdEqualTo）
        lessonTeacherExample.createCriteria()
                .andTeacherIdLike("%"+(lessonListReceive.getTeacherS())+"%");

        //得到一个课程集合
        List<LessonTeacherKey> lessonTeacherKeys
                = lessonTeacherMapper.selectByExample(lessonTeacherExample);

        //没有数据时，返回空
        if (lessonTeacherKeys.isEmpty()){
            return ResultUtil.success();
        }

        //        取出课程名集合
        List<String> lessonName = new ArrayList<>();
        for (LessonTeacherKey lessonTeacherKey:lessonTeacherKeys) {
            lessonName.add(lessonTeacherKey.getLessonName());
        }

//        添加集合条件
        criteria.andLessonNameIn(lessonName);

        //1.先开启分页
        PageHelper.startPage(lessonListReceive.getPageNumber(), lessonListReceive.getPageSize());//启动分页
//        2.执行SQL语句
        List<LessonResult> lessonResults = lessonMapper.selectLessonInfo(lessonExample);
//        3.获取分页信息
        PageInfo<LessonResult> lessonResultPageInfo = new PageInfo<>(lessonResults);//获取分页信息

        return ResultUtil.success("查询成功", lessonResults, lessonResultPageInfo.getTotal());
    }

    /**
     * 修改课程安排
     * @Author HY
     * @Description
     * @Date  2021/06/21
     * @param: lesson
     * @return
     * @return: com.group3.utils.Result
     **/
    @Override
    @Transactional
    public Result updateLesson(Lesson lesson) {

        LessonExample lessonExample = new LessonExample();
        lessonExample.createCriteria().andLessonIdEqualTo(lesson.getLessonId());

        int rs = lessonMapper.updateByExampleSelective(lesson, lessonExample);

        return rs > 0?ResultUtil.success("修改成功"):ResultUtil.error("修改失败");
    }

    /**
     * 删除课程安排
     * @Author HY
     * @Description
     * @Date  2021/06/21
     * @param: lessonId
     * @return
     * @return: com.group3.utils.Result
     **/
    @Override
    @Transactional
    public Result deleteLessonSchedule(Integer lessonId) {

        LessonExample lessonExample;
        //判断该课程是否已经上完
        lessonExample = new LessonExample();
        lessonExample.createCriteria()
                .andLessonIdEqualTo(lessonId)
//                获取系统时间、判断课程是否已经开始
                .andStartTimeLessThan(new Date());

        List<Lesson> lessons = lessonMapper.selectByExample(lessonExample);
        if (lessons == null || lessons.size() < 1){
            // 需要一个 课程已经开始，不能删除 的异常？
            throw new BusinessException(ExceptionEnum.DATABASE_OPERATION_ERR);
        }

//        删除课程
        lessonExample = new LessonExample();
        lessonExample.createCriteria().andLessonIdEqualTo(lessonId);

        int rs = lessonMapper.deleteByPrimaryKey(lessonId);

        return rs > 0?ResultUtil.success("删除成功"):ResultUtil.error("删除失败");
    }

    /**
     * 添加课程安排
     * @Author HY
     * @Description
     * @Date  2021/06/21
     * @param: lesson
     * @return
     * @return: com.group3.utils.Result
     **/
    @Override
    @Transactional
    public Result addLesson(Lesson lesson) {

        //添加课程安排
        int rs = lessonMapper.insert(lesson);

//        根据添加的课程安排的课程名查找出学生
        StudentLessonExample studentLessonExample = new StudentLessonExample();
//        添加课程名条件
        studentLessonExample.createCriteria()
                .andLessonNameEqualTo(lesson.getLessonName());

        List<StudentLesson> studentLessons = studentLessonMapper.selectByExample(studentLessonExample);
//        判断集合是否存在
        if (!studentLessons.isEmpty()) {
//            return ResultUtil.error("？？？？");
            return ResultUtil.success("该课程还未有学生哦！请先添加学生");
        }
//        根据查出的学生id生成考勤记录
        Attendance attendance = null;
//        循环学生集合，添加考勤记录
        for (StudentLesson studentLesson : studentLessons) {
            attendance = new Attendance();
            attendance.setLessonId(lesson.getLessonId());
            attendance.setStudentId(studentLesson.getStudentId());

            rs = attendanceMapper.insertSelective(attendance);
            isRs(rs);
        }

        return rs > 0?ResultUtil.success("添加成功"):ResultUtil.error("添加失败");
    }

    /**
     * 复制课程安排
     * @Author HY
     * @Description
     * @Date  2021/06/21
     * @param: lessonId
     * @return
     * @return: com.group3.utils.Result
     **/
    @Override
    @Transactional
    public Result copyLesson(Integer lessonId) {

        Lesson lesson = lessonMapper.selectByPrimaryKey(lessonId);

        int rs = lessonMapper.insert(lesson);

        return rs > 0?ResultUtil.success("添加成功"):ResultUtil.error("添加失败");
    }
}
